# -*- coding: utf-8 -*-

import sys

from PyQt5.QtCore import QObject, Qt, QPropertyAnimation, pyqtProperty, QTimer
from PyQt5.QtGui import QPixmap, QPen, QFont, QKeySequence, QPainter
from PyQt5.QtWidgets import QPushButton, QApplication, QWidget, QMainWindow, QGraphicsPixmapItem, \
    QGraphicsSimpleTextItem, QGraphicsItem, QGraphicsView, QShortcut, QGraphicsScene, QFrame
import cgitb
import sys
import resources.resource_rc
from serialPort import cm3_pb2

cgitb.enable(format='text')  # 解决pyqt5异常只要进入事件循环,程序就崩溃,而没有任何提示


class Rotation(QObject):
    def __init__(self):
        super().__init__()
        pixmap = QPixmap(":/icons/icons/arrow.png")
        scaledPixmap = pixmap.scaled(640, 640)  # 动画大小
        self.animation()
        self.pixmap_item = QGraphicsPixmapItem(scaledPixmap)
        self.pixmap_item.setTransformOriginPoint(340, 260)  # 设置中心为旋转

    def _set_rotation(self, degree):
        self.pixmap_item.setRotation(degree)  # 自身改变旋转度数

    def animation(self):
        self.anim = QPropertyAnimation(self, b'rotation')  # 动画类型
        self.anim.setDuration(1000)
        self.anim.setStartValue(0)  # 初始角度
        self.anim.setEndValue(360)
        self.anim.setLoopCount(-1)  # 设置循环旋转

    rotation = pyqtProperty(int, fset=_set_rotation)  # 属性动画改变自身数值


class GyroWindow(QGraphicsView):
    def __init__(self, parent=None):
        super(GyroWindow, self).__init__(parent)
        # 引入公共程序
        from utils.common import commonProgram
        # 引入配置文件
        self.myConfig = commonProgram.EnableConfigHandler()
        print('GyroWindow get config Version', self.myConfig.version)
        # 引入可控串口信息窗口
        commonProgram.EnableSerialPort(RecvSerialData=self.RecvSerialData)

        # 快捷键
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               双击 或者 F11')
        # 动画设置
        self.setWindowTitle('陀螺仪查看')  # 设置窗口标题
        self.rota = Rotation()
        self.graphicsScene = QGraphicsScene(self)
        self.graphicsScene.setSceneRect(0, 0, 680, 520)  # 动画 位置 这个需计算
        self.graphicsScene.addItem(self.rota.pixmap_item)
        # 显示文字
        self.text_item = QGraphicsSimpleTextItem('0')
        self.text_item.setTransformOriginPoint(340, 260)  # 设置中心为旋转
        self.text_item.setPen(QPen(Qt.red))
        self.text_item.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsMovable)
        # tipText.setScale(1.5)
        # self.text_item.setPos(0, 0)
        # self.text_item.setFont(QFont(self.font().family(), 15))
        self.graphicsScene.addItem(self.text_item)
        self.setScene(self.graphicsScene)

        # 角度记录
        self.maxDegree = 0
        self.minDegree = 0

        # 通过图标
        self.pixmapPass = QGraphicsPixmapItem(QPixmap(':/icons/icons/pass.png'))
        self.pixmapPass.setScale(0.3)
        self.pixmapPass.setZValue(1)
        self.pixmapPass.setPos(680 / 2, 520 / 2 - 100)
        self.pixmapPass.setVisible(False)
        self.graphicsScene.addItem(self.pixmapPass)

        # 首页
        self.pixmapHome = QGraphicsPixmapItem(QPixmap(':/icons/icons/home.png'))
        self.pixmapHome.setScale(0.5)
        self.pixmapHome.setZValue(1)
        self.pixmapHome.setPos(680 / 2, 520 / 2 + 100)
        self.pixmapHome.setVisible(False)
        self.pixmapHome.myName = 'home'
        self.graphicsScene.addItem(self.pixmapHome)

        self.setFrameStyle(QFrame.NoFrame)  # 无Frame边框
        # 隐藏滚动条
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # 以鼠标所在位置为锚点进行缩放
        self.setTransformationAnchor(self.AnchorUnderMouse)

        # 平滑缩放
        # self.pixmapItem.setTransformationMode(Qt.SmoothTransformation)
        self.setRenderHints(QPainter.Antialiasing |
                            QPainter.SmoothPixmapTransform)

    def mousePressEvent(self, evt):
        self.item = self.get_item_at_click(evt)
        pt = evt.pos()  # 获取鼠标坐标--view坐标
        QGraphicsView.mousePressEvent(self, evt)
        if self.item is not None:
            # print('self.item: ', self.item)
            try:
                myName = self.item.myName
                if 'home' in myName:
                    # print('home')
                    self.close()
            except Exception as e:
                pass

    def WindowSizeFun(self):
        # print(toStatus)
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'

    def RecvSerialData(self, dictData: dict):
        # 用于接收Form2发过来的数据
        # dataStr = dictData.get("data", None)  # num2 就是子界面传递过来的数据
        if self.isVisible():
            self.DataHandleFun(dictData)
        # # type: send-发往串口，statusbar-显示在statusbar(状态栏)，text,.., - 显示在 textBrowser, null-不需要显示
        # print('-'*30)

    def DataHandleFun(self, dataDict: dict):
        typeStr = dataDict.get('type', 'null').strip()
        # if typeStr == 'send':
        #     dataDict['type'] = 0
        #     self.displaySignal.emit(dataDict)
        if typeStr == 'rece_protobuf':
            display = dataDict.get('data', '')
            # dataStr = 'ListDisplay:{},{},{},{},{},{},{}'.format(display.id, display.input.key, display.input.rot,
            #                                                     display.status.temp, display.status.light,
            #                                                     display.version.hw, display.version.sw)
            # print(type(display),display)
            # print('-'*5,display.id)
            if display.msg_type == cm3_pb2.Status:
                myDegree = display.status.gyro / 2 - 100
                if myDegree > self.maxDegree:
                    self.maxDegree = myDegree
                if myDegree < self.minDegree:
                    self.minDegree = myDegree
                self.rota._set_rotation(-myDegree)
                self.text_item.setRotation(-myDegree)
                self.text_item.setText(str(myDegree))
                if self.maxDegree - self.minDegree > 100:
                    self.pixmapPass.setVisible(True)
                    self.pixmapHome.setVisible(True)
                    self.myConfig.passTestItems.add('Gyro')

    def mouseDoubleClickEvent(self, event):
        self.WindowSizeFun()
        super().mouseDoubleClickEvent(event)

    def get_item_at_click(self, e):
        pos = e.pos()
        item = self.itemAt(pos)
        return item


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = GyroWindow()  # 实体化 类
    win.show()
    sys.exit(app.exec_())
